package com.example.demo.servlet;

import com.example.demo.task.IssueManageTask;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

//@WebServlet(loadOnStartup = 0, urlPatterns = "/init")
public class InitTaskServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;

    private Logger logger = LoggerFactory.getLogger(InitTaskServlet.class);

    //创建一个定长的线程池，而且支持定时的以及周期性的任务执行，支持定时及周期性任务执行。
    //Runtime.getRuntime().availableProcessors()是用来获取电脑可以用的CPU数目
    protected ScheduledExecutorService executor = Executors
            .newScheduledThreadPool(Runtime.getRuntime().availableProcessors());

    @Override
    public void init() {
        logger.info("initServlet initing");

        //当 Web 应用集成 Spring 容器后，代表 Spring 容器的WebApplicationContext对象将以
        //WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE 为键存放在ServletContext的属性列表中。
        //我们可以通过工具类 WebApplicationContextUtils 方便的获取 WebApplicationContext
        // getServletContext() 是父类中获取 ServletContext 的方法,这里将 ServletContext 作为参数传入那个获取方法
        ApplicationContext ctx = WebApplicationContextUtils.getRequiredWebApplicationContext(getServletContext());

        IssueManageTask generateIssueTask=(IssueManageTask)ctx.getBean(IssueManageTask.class);
        executor.scheduleWithFixedDelay(generateIssueTask,1L, 5L, TimeUnit.SECONDS);


    }

    @Override
    public void destroy() {
        executor.shutdown();

        logger.info("initServlet destoryed");
    }
}